<?php

class RegisterController extends Controller {

    public function actionIndex() {

        if (!Yii::app()->user->isGuest) {
            $this->redirect(array('/index'));
        }

        $model = new RegisterForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'register-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['RegisterForm'])) {
            $model->birthday = $_POST['RegisterForm']['birthday'];
            $model->attributes = $_POST['RegisterForm'];
            $model->time_of_birthday = $_POST['time_of_birthday'];

            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->register()) {
                EmailUtil::sendEmail($model->username, EmailUtil::HEADER_REGISTER, EmailUtil::getRegisterMessage($model->username));
//                $this->redirect(Yii::app()->user->returnUrl);
                $message = Yii::t('wait', 'regisSuccess').$model->username;
                $redirectPage = Yii::app()->getBaseUrl(true).'/index.php?r=login';
                $this->redirect(array('/wait', 'message' => $message, 'redirectPage' => $redirectPage));
                return;
            }
        }

        // display the login form
        $this->render("index", array('model' => $model));
    }

    public function actionActivate() {
        $cust_id = $_GET["id"];
        $key = $_GET["key"];

        if (!empty($cust_id) && !empty($key)) {
            $customer = Customer::model()->findByPk($cust_id);
            if ($customer->activate_key == $key) {
                $customer->active = 1;
                if ($customer->update()) {
                    $message = Yii::t('wait', 'activateSuccess');
                    $redirectPage = Yii::app()->getBaseUrl(true).'/index.php?r=login';
                    $this->redirect(array('/wait', 'message' => $message, 'redirectPage' => $redirectPage));
                    return;
                }
            }
        }

        Yii::app()->user->setFlash('activate', Yii::t('register', 'activate_fail'));
        $this->render("activate");
    }

}
